package com.kinsin.kinsinutil

import android.content.Context
import android.content.SharedPreferences
import java.util.concurrent.ConcurrentHashMap
import androidx.core.content.edit

/**
 * 共享参数工具类
 * @author kinsin
 */
class SharedPreferenceHelper private constructor(context: Context, fileName: String) {
    private val sharedPreferences: SharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)

    /**
     * 请注意，默认的提交是延迟提交的，所以调用了apply()方法后，需要等待一段时间才能看到修改后的结果。
     * @param key 键
     * @param value 值
     * @param commit 是否立即提交，默认为false，即延迟提交。
     */
    fun put(key: String, value: Any, commit: Boolean = false) {
        sharedPreferences.edit(commit) {
            when (value) {
                is String -> putString(key, value)
                is Int -> putInt(key, value)
                is Boolean -> putBoolean(key, value)
                is Float -> putFloat(key, value)
                is Long -> putLong(key, value)
                else -> throw IllegalArgumentException("Unsupported type.")
            }
        }
    }

    @Suppress("UNCHECKED_CAST")
    fun <T> get(key: String, defaultValue: T): T {
        return when (defaultValue) {
            is String -> sharedPreferences.getString(key, defaultValue) as T
            is Int -> sharedPreferences.getInt(key, defaultValue) as T
            is Boolean -> sharedPreferences.getBoolean(key, defaultValue) as T
            is Float -> sharedPreferences.getFloat(key, defaultValue) as T
            is Long -> sharedPreferences.getLong(key, defaultValue) as T
            else -> throw IllegalArgumentException("Unsupported type.")
        }
    }

    fun remove(key: String) {
        sharedPreferences.edit() { remove(key) }
    }

    fun clear() {
        sharedPreferences.edit() { clear() }
    }

    companion object {
        private val instances = ConcurrentHashMap<String, SharedPreferenceHelper>()

        fun getInstance(context: Context, fileName: String = "MySharedPreferences"): SharedPreferenceHelper {
            val appContext = context.applicationContext
            return instances.getOrPut(fileName) {
                SharedPreferenceHelper(appContext, fileName)
            }
        }
    }
}